package com.hktf.moedokilock.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;


import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hktf.corelib.constant.KEYS;
import com.hktf.corelib.jsonbean.response.StringResult;
import com.hktf.corelib.utils.ButtonUtils;
import com.hktf.corelib.utils.CommUtils;
import com.hktf.corelib.utils.Config;
import com.hktf.corelib.utils.FileUtil;
import com.hktf.corelib.utils.FileUtils;
import com.hktf.corelib.utils.MMKVUtils;
import com.hktf.corelib.utils.UIUtils;
import com.hktf.moedokilock.R;
import com.hktf.moedokilock.adapter.WidgetItemAdapter;
import com.hktf.moedokilock.widget.PickDateFormatPopWindow;
import com.hktf.moedokilock.widget.PickWidgetPopWindow;
import com.hktf.uilib.app.BaseActivity;
import com.hktf.uilib.bean.lock.WidgetItem;
import com.hktf.uilib.callback.BaseCallBackNew;
import com.hktf.uilib.engine.DriverEngine;
import com.hktf.uilib.utils.DisplayUtil;
import com.hktf.uilib.utils.ImageUtilNew;
import com.hktf.uilib.utils.LockScreenUtil;
import com.hktf.uilib.utils.ToastUtils;
import com.hktf.uilib.widget.NoSpaceTextClock;
import com.hktf.uilib.widget.PickFontAndColorPopWindow;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class PreviewWallpaperActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = "PreviewWallpaperActivity";
    private android.widget.ImageView iv;
    private android.widget.TextView tvCancel;
    private android.widget.TextView tvConfirm;
    //hexunwu TODO 退出应用提示框

    private RelativeLayout rlTop;
    private RelativeLayout rlTime;
//    private com.hktf.uilib.widget.NoSpaceTextView tvTime;
    private NoSpaceTextClock tvTime;
    private RelativeLayout rlDate;
    private TextView tvDate;
    private FrameLayout rlCustomer;
    private LinearLayout ll;
    private com.yqritc.scalablevideoview.ScalableVideoView videoView;
    private androidx.recyclerview.widget.RecyclerView recyclerView;
    private FrameLayout flRoot;


    @Override
    public int getLayoutResID() {
        return R.layout.act_previewwallpaper;
    }

    @Override
    public void initView() {
        iv = findViewById(R.id.iv);
        tvCancel = findViewById(R.id.tv_cancel);
        tvConfirm = findViewById(R.id.tv_confirm);
        rlTop =  findViewById(R.id.rl_top);
        rlTime = findViewById(R.id.rl_time);
        tvTime = findViewById(R.id.tv_time);
        rlDate =  findViewById(R.id.rl_date);
        tvDate = findViewById(R.id.tv_date);
        ll=findViewById(R.id.ll);
        rlCustomer = findViewById(R.id.rl_customer);
        rlTime.setOnClickListener(this);
        rlDate.setOnClickListener(this);
        rlCustomer.setOnClickListener(this);
        videoView = findViewById(R.id.video_view);
        recyclerView = findViewById(R.id.recyclerView);
        flRoot = findViewById(R.id.fl_root);
        flRoot.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                changeStrokeBg(!showStrokebg);
            }
        });
    }
    private boolean showStrokebg=true;

    private void changeStrokeBg(boolean showStrokebg){
        this.showStrokebg=showStrokebg;
        if(showStrokebg){
            rlDate.setBackgroundResource(com.hktf.uilib.R.drawable.white_blod_stroke_bg);
            rlTime.setBackgroundResource(com.hktf.uilib.R.drawable.white_blod_stroke_bg);
            rlCustomer.setBackgroundResource(com.hktf.uilib.R.drawable.white_blod_stroke_bg);
        }else {
            rlDate.setBackgroundResource(com.hktf.uilib.R.drawable.transparent);
            rlTime.setBackgroundResource(com.hktf.uilib.R.drawable.transparent);
            rlCustomer.setBackgroundResource(com.hktf.uilib.R.drawable.transparent);
        }
        if (widgetItemAdapter != null) {
            widgetItemAdapter.setShowDelete(showStrokebg);
        }
    }


    @Override
    public boolean showStatusBarAndNavBar() {
        return false;
    }

    @Override
    public void initListener() {
        tvCancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();

            }
        });
        tvConfirm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                saveCheckLock(resId);
                finish();

            }
        });

    }
    private int resId;
    private int type;//0预览 1锁屏

    @Override
    public void initData() {
        Intent intent = getIntent();
        resId = intent.getIntExtra("resId", -1);
        type = intent.getIntExtra("type", 0);
        if(type==1){
            rlTop.setVisibility(View.GONE);
            resId= MMKVUtils.getInteger(KEYS.LOCK_RESID,R.drawable.lock0);
        }
        LockScreenUtil.initLock(this,iv,tvTime,tvDate);
        ImageUtilNew.loadImageFitXY(this,resId, DisplayUtil.getMetricsWidth(this),DisplayUtil.getMetricsHeight(this),iv);
        preColor = MMKVUtils.getInteger(KEYS.FONT_COLOR,UIUtils.getColor(com.hktf.uilib.R.color.owner_blue));
        try {
//            String filepath = Config.getDownLoadPath()+"3.mp4";
            String filepath = Config.getDownLoadPath()+"1";
            File file = new File(filepath);
            if (!file.exists()) {
                FileUtil.copyAssetFileToSD(this,"1.mp4",filepath);
            }

            System.out.println(filepath+" isExist="+file.exists());
            videoView.setDataSource(filepath);
            videoView.setLooping(true);
            videoView.prepareAsync(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    videoView.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

        fillWidgetData();
    }

    private void getDujitang(WidgetItem widgetItem){
        DriverEngine.getDujitang(new BaseCallBackNew<StringResult>(StringResult.class){
            @Override
            public void onSuccess(Response<StringResult> response) {
                StringResult body = response.body();
                String data = body.getData();
                widgetItem.setTitle(data);
                widgetItemAdapter.notifyDataSetChanged();
            }
        });
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


    @Override
    protected void onStart() {
        super.onStart();

    }




    public void onDestroy() {
        super.onDestroy();
        if (videoView != null) {
            videoView.stop();
        }
    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();

    }



    @Override
    public void onClick(View view) {
        //防止多次点击
        if (ButtonUtils.isFastDoubleClick()) {
            return;
        }
        int id = view.getId();
        if(id==R.id.rl_time){
            changeStrokeBg(true);
            rlTop.setVisibility(View.INVISIBLE);
            if (pickFontAndColorPopWindow!=null&&pickFontAndColorPopWindow.isShowing()) {
                pickFontAndColorPopWindow.dismiss();
            }
            pickFontAndColorPopWindow=new PickFontAndColorPopWindow(this, preColor, new PickFontAndColorPopWindow.MyListener() {
                @Override
                public void onPickFont(int font, int position) {
                    MMKVUtils.putInteger(KEYS.FONT,position);

                    CommUtils.setfont(PreviewWallpaperActivity.this,tvTime,font);

                }

                @Override
                public void onPickColor(int color) {
                    changeColor(color);

                }

                @Override
                public void onDismiss() {
                    rlTop.setVisibility(View.VISIBLE);
                }
            });

            pickFontAndColorPopWindow.showAtLocation(ll, Gravity.BOTTOM,0,0);
        }else if(id==R.id.rl_date){
            changeStrokeBg(true);
            rlTop.setVisibility(View.INVISIBLE);
            if (pickDateFormatPopWindow!=null&&pickDateFormatPopWindow.isShowing()) {
                pickDateFormatPopWindow.dismiss();
            }
            pickDateFormatPopWindow=new PickDateFormatPopWindow(this, new PickDateFormatPopWindow.MyListener() {

                @Override
                public void onPick(String dateFormatStr) {
                    SimpleDateFormat simpleDateFormat=new SimpleDateFormat(dateFormatStr);
                    tvDate.setText(simpleDateFormat.format(System.currentTimeMillis()));
                    MMKVUtils.putString(KEYS.DATE_FORMAT,dateFormatStr);

                }

                @Override
                public void onDismiss() {
                    rlTop.setVisibility(View.VISIBLE);
                }
            });

            pickDateFormatPopWindow.showAtLocation(ll, Gravity.BOTTOM,0,0);
        }else if(id==R.id.rl_customer){
            showWidgetPickPopWindow();
        }

    }
    private void showWidgetPickPopWindow(){
        if(widgetSpace==Config.WIDGET_SPACE){
            showInfoDlg(UIUtils.getString(com.hktf.uilib.R.string.no_space),null);
            return;
        }


        changeStrokeBg(true);
        rlTop.setVisibility(View.INVISIBLE);
        if (pickWidgetPopWindow!=null&&pickWidgetPopWindow.isShowing()) {
            pickWidgetPopWindow.dismiss();
        }

        pickWidgetPopWindow=new PickWidgetPopWindow(this, new PickWidgetPopWindow.MyListener() {

            @Override
            public void onPick(WidgetItem widgetItem, int  position) {

                onWidgetItemPick(widgetItem,position);

            }

            @Override
            public void onDismiss() {
                rlTop.setVisibility(View.VISIBLE);
            }
        });

        pickWidgetPopWindow.showAtLocation(ll, Gravity.BOTTOM,0,0);
    }
    private List<WidgetItem> listWidgets =new ArrayList<>();
    private int widgetSpace;
    private void onWidgetItemPick(WidgetItem widgetItem, int  position){
        int widgetWeight = widgetItem.getWeight();
        int total=widgetWeight+widgetSpace;
        if(total>Config.WIDGET_SPACE){
            ToastUtils.showToast(this,"放不下了！");
            return;
        }
        widgetSpace=total;

        int itemType = widgetItem.getItemType();
        switch (itemType) {
            case WidgetItem.TYPE_JITANG:
                getDujitang(widgetItem);
                break;
            case WidgetItem.TYPE_TEXT2:
                break;
            case WidgetItem.TYPE_TEXT_CIRCLE:
                break;
        }


        listWidgets.add(widgetItem);
        fillWidgetData();
    }
    private WidgetItemAdapter widgetItemAdapter;
    private WidgetItem emptyWidgetItem = new WidgetItem();

    private void fillWidgetData(){
        listWidgets.remove(emptyWidgetItem);

        //判断是否需要放入空白控件
        int space = Config.WIDGET_SPACE - widgetSpace;
        if(space>0){
            emptyWidgetItem.setWeight(space);
            emptyWidgetItem.setItemType(-1);
            listWidgets.add(emptyWidgetItem);
        }

        if (widgetItemAdapter == null) {
            GridLayoutManager layoutManager = new GridLayoutManager(context, Config.WIDGET_SPACE);
            recyclerView.setLayoutManager(layoutManager);
            widgetItemAdapter=new WidgetItemAdapter(listWidgets);
            widgetItemAdapter.setShowDelete(true);
            widgetItemAdapter.setShowLine(false);
            recyclerView.setAdapter(widgetItemAdapter);//666
            widgetItemAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    showWidgetPickPopWindow();
                }
            });
            widgetItemAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    WidgetItem item = listWidgets.remove(position);
                    int id = view.getId();
                    if (id==R.id.fl_delete){
                        widgetSpace=widgetSpace-item.getWeight();//减去空间
                        fillWidgetData();
                    }
                }
            });
            layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup(){

                @Override
                public int getSpanSize(int position) {
                    return widgetItemAdapter.getItem(position).getWeight();
                }
            });
        }else {
            widgetItemAdapter.setNewData(listWidgets);
        }
    }
    private PickDateFormatPopWindow pickDateFormatPopWindow;
    private PickWidgetPopWindow pickWidgetPopWindow;
    private PickFontAndColorPopWindow pickFontAndColorPopWindow;
    private int preColor=-1;

    private void changeColor(int color){
        preColor=color;
        MMKVUtils.putInteger(KEYS.FONT_COLOR,color);
        tvTime.setTextColor(color);
        tvDate.setTextColor(color);
    }






}
